﻿<%@ Page Language="C#" MasterPageFile="~/SIPO.master" AutoEventWireup="false" CodeFile="recImpositionCurrentform.aspx.cs"
    Inherits="SIPO.Web.Forms.Transaction.recImpositionCurrentform" %>

<asp:Content ID="ctnBody" ContentPlaceHolderID="body" runat="server">
    <link type="text/css" rel="stylesheet" href="<%= ResolveUrl("~/styles/ui.jqgrid.css") %>" />
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.wrapper.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.fileupload.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.iframe-transport.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.inputmask.bundle.min.js") %>" type="text/javascript"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/i18n/grid.locale-id.js") %>"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
    <style type="text/css">
        .ui-autocomplete
        {
            max-height: 100px;
            overflow-y: auto; /* prevent horizontal scrollbar */
            overflow-x: hidden; /* add padding to account for vertical scrollbar */
            padding-right: 20px;
        }
        .custom-combobox
        {
            position: relative;
            display: inline-block;
        }
        .custom-combobox-toggle
        {
            position: absolute;
            top: 0;
            bottom: 0;
            margin-left: -1px;
            padding: 0; /* support: IE7 */
            height: 1.7em;
            top: 0.1em;
        }
        .custom-combobox-input
        {
            margin: 0;
            padding: 0.3em;
        }
        .style1
        {
            width: 225px;
        }
        .style2
        {
            width: 111px;
        }
    </style>
    <script type="text/javascript">

        $(document).ready(function () {

            $("#btnClose").button({ icons: { primary: "ui-icon-close"} });
            $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });

        });          

    </script>
    <script type="text/javascript" language="javascript">

        (function ($) {

            $.widget("custom.combobox", {
                _create: function () {
                    this.wrapper = $("<span>")
          .addClass("custom-combobox")
          .insertAfter(this.element);

                    this.element.hide();
                    this._createAutocomplete();
                    this._createShowAllButton();
                },

                _createAutocomplete: function () {
                    var selected = this.element.children(":selected"),
          value = selected.val() ? selected.text() : "";

                    var width = this.element.width() > 100 ? "style='width:" + this.element.width() + "px';" : "";

                    this.input = $("<input " + width + ">")
          .appendTo(this.wrapper)
          .val(value)
          .attr("title", "")
          .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
          .autocomplete({
              autoFocus: true,
              selectFirst: true,
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
          })
          .tooltip({
              tooltipClass: "ui-state-highlight"
          });

                    this._on(this.input, {
                        autocompleteselect: function (event, ui) {
                            ui.item.option.selected = true;
                            this._trigger("select", event, {
                                item: ui.item.option
                            });

                            var idOfCaller = this.element.attr('id');
                            switch (idOfCaller.toLowerCase()) {
                                case ("body_ddldebtor"):
                                    $('#<%= ddlDebtor.ClientID%>').change();
                                    break;
                                case ("body_ddlsubsector"):
                                    $('#<%= ddlSubSector.ClientID%>').change();
                                    break;
                                case ("body_ddlsubsubsector"):
                                    $('#<%= ddlSubSubSector.ClientID%>').change();
                                    break;
                                default:
                                    break;
                            }

                        },

                        autocompletechange: "_removeIfInvalid"
                    });
                },

                _createShowAllButton: function () {
                    var input = this.input,
          wasOpen = false;

                    $("<a>")
          .attr("tabIndex", -1)
          .attr("title", "Tampilkan Semua Item")
          .tooltip()
          .appendTo(this.wrapper)
          .button({
              icons: {
                  primary: "ui-icon-triangle-1-s"
              },
              text: false
          })
          .removeClass("ui-corner-all")
          .addClass("custom-combobox-toggle ui-corner-right")
          .mousedown(function () {
              wasOpen = input.autocomplete("widget").is(":visible");
          })
          .click(function () {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                  return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
          });
                },

                _source: function (request, response) {
                    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                    response(this.element.children("option").map(function () {
                        var text = $(this).text();
                        if (this.value && (!request.term || matcher.test(text)))
                            return {
                                label: text,
                                value: text,
                                option: this
                            };
                    }));
                },

                _removeIfInvalid: function (event, ui) {

                    // Selected an item, nothing to do
                    if (ui.item) {
                        return;
                    }

                    // Search for a match (case-insensitive)
                    var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
                    this.element.children("option").each(function () {
                        if ($(this).text().toLowerCase() === valueLowerCase) {
                            this.selected = valid = true;
                            return false;
                        }
                    });

                    // Found a match, nothing to do
                    if (valid) {
                        return;
                    }

                    // Remove invalid value
                    this.input
          .val("")
          .attr("title", value + " tidak ditemukan")
          .tooltip("open");
                    this.element.val("");
                    this._delay(function () {
                        this.input.tooltip("close").attr("title", "");
                    }, 2500);
                    this.input.data("ui-autocomplete").term = "";
                },

                _destroy: function () {
                    this.wrapper.remove();
                    this.element.show();
                },
                autocomplete: function (value, text) {
                    this.element.val(value);
                    this.input.val(text);
                }
            });
        })(jQuery);

        $(function () {

            $('#<%= ddlDebtor.ClientID %>').combobox();
            $('#<%= ddlSubSector.ClientID%>').combobox();
            $('#<%= ddlSubSubSector.ClientID%>').combobox();
        });

    </script>
    <script type="text/javascript">
        $(function () {
            var acceptedFiles = [];
            var maxSize;

            var handlerUrl = '<%= ResolveUrl("~/ajaxhandler/loaddata/getparameters.ashx") %>';
            $.getJSON(handlerUrl)
            .done(function (datas) {
                $.each(datas, function (i, data) {
                    if (data.ParameterCode.toLowerCase() == 'allowedfiletype') {
                        var files = data.Value.split(',');
                        $.each(files, function (i, item) {
                            var file = $.trim(item);
                            acceptedFiles.push(file);
                        });
                    } else if (data.ParameterCode.toLowerCase() == 'maxuploadsizekb') {
                        maxSize = data.Value;
                    }
                });
            });

            $('#frmMasterPage').fileupload({
                autoUpload: false, replaceFileInput: false, singleFileUploads: true,
                add: function (e, data) {
                    if (data.files[0].name.lastIndexOf('.')) {

                        var ext = data.files[0].name.substr(data.files[0].name.lastIndexOf('.') + 1);
                        var sizeFile = Math.round((data.files[0].size / 1024));
                        var index = $.inArray(ext, acceptedFiles);

                        var errMsg = '';
                        var money = parseFloat(sizeFile);
                        var sizeMB = Math.round(maxSize / 1024);

                        //$('#btnSave').button('enable');

                        if (index < 0)
                            errMsg = '- File harus berformat ' + acceptedFiles + ' \n';

                        if (sizeFile > parseInt(maxSize)) {
                            errMsg += '- Ukuran file harus tidak boleh lebih dari ' + sizeMB + ' Mb atau ' + maxSize + ' KB \n';
                            errMsg += '- Nama file ' + data.files[0].name + '\n- Ukuran file = ' + money.formatMoney(0, ".", ",") + ' KB';
                        }

                        if (errMsg != '') {
                            errMsg = 'File tidak dapat di upload\nBerikut ada kesalahan saat upload dokumen / file.\n' + errMsg;
                            $('#fileUpload').val('');
                            $('#divFileRemarks').html('');
                            alert(errMsg);
                            //$('#btnSave').button('disable');
                        }
                        else
                            $('#divFileRemarks').html('<span style="font-size:small;">Ukuran file = ' + money.formatMoney(0, ".", ",") + ' KB</span>');
                    }
                }
            });

        });
    </script>
    <script type="text/javascript">

        $(document).ready(function () {
            $("#<%= txtTarifMin.ClientID %>").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            $("#<%= txtTarifMax.ClientID %>").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            $("#<%= hfTarifValue.ClientID %>").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            $("#<%= txtDebtorValue.ClientID %>").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            $("#<%= txtOJKValue.ClientID %>").inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            // 1. prepare the validation rules and messages.
            var rules = {
                '<%= ddlDebtor.UniqueID %>': "required",
                '<%= ddlSubSubSector.UniqueID %>': "required",
                '<%= ddlSubSector.UniqueID %>': "required",
                '<%= txtDebtorValue.UniqueID %>': "required",
                '<%= txtOJKValue.UniqueID %>': "required",
                '<%= ddlTahunLapKeu.UniqueID %>': "required"
            };

            var messages = {
                '<%= ddlDebtor.UniqueID %>': "Debitur harus dipilih",
                '<%= ddlSubSubSector.UniqueID %>': "Sub sub sektor harus dipilih",
                '<%= ddlSubSector.UniqueID %>': "Sub sektor harus dipilih",
                '<%= txtDebtorValue.UniqueID %>': "Nilai pengenaan Debitur harus di isi",
                '<%= txtOJKValue.UniqueID %>': "Nilai pengenaan OJK harus di isi",
                '<%= ddlTahunLapKeu.UniqueID %>': "Tahun laporan keuangan harus di isi"
            };
            // 2. Initiate the validator
            var validator = new jQueryValidatorWrapper("frmMasterPage", rules, messages);

            var debtorId = "<%= base.DebtorID %>";
            if (debtorId != "")
                $('#trnilaipengenaanOJK').hide();
            else
                $('#trnilaipengenaanOJK').show();
            GetDebtor();

            $('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
            $('#<%= ddlSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sektor --");

            function Clear() {
                $('#<%= hfIsFormula.ClientID %>').val('');
                $('#<%= hfTarifId.ClientID %>').val('');
                $('#<%= txtPercentage.ClientID %>').val('');
                $('#<%= txtTarifMax.ClientID %>').val('');
                $('#<%= txtTarifMin.ClientID %>').val('');
                $('#<%= hfDebtorSectorId.ClientID %>').val('');
                $('#<%= hfTarifValue.ClientID %>').val('');
                $('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
                $('#<%= ddlSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sektor --");
                $('#<%= txtDebtorValue.ClientID %>').val('');
                $('#<%= txtOJKValue.ClientID %>').val('');
                $('#<%= ddlImpositionBase.ClientID %>').val('');
                $('#fileUpload').val('');
                $('#divFileRemarks').html('');
                $('#<%= ddlTahunLapKeu.ClientID %>').val('');
            }

            $('#<%= ddlSubSubSector.ClientID %>').change(function () {
                $('#<%= ddlTahunLapKeu.ClientID %>').val('');
                $('#<%= txtDebtorValue.ClientID %>').val('');
                $('#<%= txtOJKValue.ClientID %>').val('');
                refreshGrid();
                GetTariff();
                //LoadYearReport();
            });

            $('#<%= ddlSubSector.ClientID %>').change(function () {
                GetSubSubSector();
            });

            $('#<%= ddlDebtor.ClientID %>').change(function () {
                //$('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
                Clear();
                GetSubSector();
                //                $('#<%= ddlSubSubSector.ClientID %>').find('option:not(:first)').remove();
                //                var debtorId = $('#<%= ddlDebtor.ClientID%> option:selected').val();
                //                $subSubSectors = $('#<%= ddlSubSubSector.ClientID %>')
                //                $subSectors = $('#<%= ddlSubSector.ClientID%>');
                //                if (debtorId > 0) {
                //                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsubsector.ashx?method=getbyDebtorId&debtorid=") %>';
                //                    $.ajax({
                //                        type: 'POST',
                //                        url: handlerUrl + debtorId,
                //                        contentType: 'application/json',
                //                        dataType: 'json',
                //                        success: function (datasubsubs) {
                //                            if (datasubsubs.length > 1) {
                //                                $subSubSectors.get(0).options.length = 0;
                //                                $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                //                                $.each(datasubsubs, function (i, datasubsub) {
                //                                    $subSubSectors.append('<option value="' + datasubsub.SubSubSectorID + '">' + datasubsub.SubSubSectorCode + ' - ' + datasubsub.SubSubSectorName + '</option>');
                //                                });
                //                                $subSubSectors.combobox('autocomplete', "", "-- pilih sub sub sektor --");
                //                            }
                //                            else {
                //                                $subSubSectors.append('<option value="' + datasubsubs[0].SubSubSectorID + '">' + datasubsubs[0].SubSubSectorCode + ' - ' + datasubsubs[0].SubSubSectorName + '</option>');
                //                                $subSubSectors.combobox('autocomplete', datasubsubs[0].SubSubSectorID, datasubsubs[0].SubSubSectorCode + ' - ' + datasubsubs[0].SubSubSectorName);
                //                                //$subSubSectors.trigger("change");
                //                            }
                //                            GetSubSector();
                //                        },
                //                        error: function () {
                //                            alert('Error!');
                //                        }
                //                    });
                //                }
                //                else {
                //                    $subSubSectors.get(0).options.length = 0;
                //                    $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                //                }
            });

            function setGrid() {
                var year = $('#<%= ddlTahunLapKeu.ClientID %>').val();
                var debtorid = $('#<%= ddlDebtor.ClientID %>').val();
                var debtorsectorid = $('#<%= hfDebtorSectorId.ClientID %>').val();
                //alert('setgrid:debtorid:' + debtorid + ',debtorsector=' + debtorsectorid);
                if (year != "" && debtorid != "") {
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recCalculationhandler.ashx") %>';
                    $('#table').jqGrid({
                        url: handlerUrl + '?method=getdata&yearreport=' + year + '&debtorid=' + debtorid + '&debtorsectorid=' + debtorsectorid + '',
                        datatype: 'json',
                        colNames: ['ID', 'Tahap', 'Jatuh Tempo', 'Nilai'],
                        colModel: [
                { name: 'CalculationID', hidden: true, index: 'CalculationID', width: 5 },
           		{ name: 'recBilling.ForPayment', index: 'recBilling.ForPayment', width: 100, align: 'center' },
                { name: 'recBilling.DueDate', index: 'recBilling.DueDate', width: 100, formatter: 'date', formatoptions: { newformat: 'd M Y' }, align: 'center' },
                { name: 'recBilling.Value', index: 'recBilling.Value', width: 200, formatter: 'currency', formatoptions: { prefix: '', suffix: '', thousandsSeparator: ',' }, align: 'right' }
           	],
                        rowNum: 10,
                        id: 'CalculationID',
                        rowList: [5, 10, 15, 20],
                        pager: '#pager',
                        sortname: 'recCalculation.CalculationID',
                        sortorder: "asc",
                        viewrecords: true,
                        jsonReader: { repeatitems: false },
                        height: '100%',
                        caption: 'Iuran Berkala',
                        ajaxGridOptions: { cache: false }
                    })
                }
            }

            function refreshGrid() {
                setTimeout("$('#table').trigger('reloadGrid');", 1000);
                var year = $('#<%= ddlTahunLapKeu.ClientID %>').val();
                var debtorid = $('#<%= ddlDebtor.ClientID %>').val();
                var debtorsectorid = $('#<%= hfDebtorSectorId.ClientID %>').val();
                //alert('refreshGrid:debtorid:' + debtorid + ',debtorsector=' + debtorsectorid);
                if (year != "" && debtorid != "") {
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recCalculationhandler.ashx") %>';
                    jQuery('#table').jqGrid('setGridParam', { url: handlerUrl + '?method=getdata&yearreport=' + year + '&debtorid=' + debtorid + '&debtorsectorid=' + debtorsectorid + '' }).trigger("reloadGrid");
                }
            }

            function GetTariff() {
                var debtorId = $('#<%= ddlDebtor.ClientID%> option:selected').val();
                var subsubsectorId = $('#<%= ddlSubSubSector.ClientID%> option:selected').val();
                $subSectors = $('#<%= ddlSubSector.ClientID %>');
                $subSubSectors = $('#<%= ddlSubSubSector.ClientID %>');
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/gettarifbysubsubsectorid.ashx?subSubSectorId=' + subsubsectorId + '&transtype=iuranberkala&debtorId=' + debtorId + ' ") %>';
                if (subsubsectorId > 0) {
                    jQuery.ajax({
                        type: 'POST',
                        url: handlerUrl,
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (data) {
                            if (data.TariffID != 0) {
                                $('#<%= hfIsFormula.ClientID %>').val(data.IsFormula);
                                $('#<%= hfTarifId.ClientID %>').val(data.TariffID);
                                $('#<%= hfDebtorSectorId.ClientID %>').val(data.DebtorSectorId);
                                var unformattarifvalue = parseFloat(data.Value);
                                //$('#<%= hfTarifValue.ClientID %>').val(unformattarifvalue.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= hfTarifValue.ClientID %>').val(data.Value); // Set to id-ID format
                                var unformattarifMax = parseFloat(data.MaxValue);
                                //$('#<%= txtTarifMax.ClientID %>').val(unformattarifMax.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtTarifMax.ClientID %>').val(data.MaxValue); // Set to id-ID format
                                var unformattarifMin = parseFloat(data.MinValue);
                                //$('#<%= txtTarifMin.ClientID %>').val(unformattarifMin.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtTarifMin.ClientID %>').val(data.MinValue); // Set to id-ID format

                                $('#<%= txtPercentage.ClientID %>').val(data.Percentage);
                                if (data.ImpositionBaseId != 0)
                                    $('#<%= ddlImpositionBase.ClientID%>').val(data.ImpositionBaseId);
                                if (data.IsFormula == 0)
                                    $('#btnSave').button('disable', true);
                            }
                            else {
                                alert('Jenis Usaha ini belum ada Tarif nya!');
                                $subSubSectors.get(0).options.length = 0;
                                $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sector --", "");
                                $subSectors.get(0).options.length = 0;
                                $subSectors.get(0).options[0] = new Option("-- pilih sub sector --", "");
                                $('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
                                $('#<%= ddlSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sektor --");
                                $('#<%= ddlDebtor.ClientID %>').combobox('autocomplete', "", "-- pilih debitur --");
                                $('#<%= hfIsFormula.ClientID %>').val('');
                                $('#<%= hfTarifId.ClientID %>').val('');
                                $('#<%= txtPercentage.ClientID %>').val('');
                                $('#<%= txtTarifMax.ClientID %>').val('');
                                $('#<%= txtTarifMin.ClientID %>').val('');
                                $('#<%= hfDebtorSectorId.ClientID %>').val('');
                                $('#<%= hfTarifValue.ClientID %>').val('');
                                $('#<%= ddlImpositionBase.ClientID%>').val('');
                                $('#<%= ddlTahunLapKeu.ClientID %>').val('');
                                $('#<%= txtDebtorValue.ClientID %>').val('');
                                $('#<%= txtOJKValue.ClientID %>').val('');
                            }
                        },
                        error: function () {
                            alert('Error!');
                        }
                    });
                }
                else {
                    $('#<%= hfIsFormula.ClientID %>').val('');
                    $('#<%= hfTarifId.ClientID %>').val('');
                    $('#<%= txtPercentage.ClientID %>').val('');
                    $('#<%= txtTarifMax.ClientID %>').val('');
                    $('#<%= txtTarifMin.ClientID %>').val('');
                    $('#<%= hfDebtorSectorId.ClientID %>').val('');
                    $('#<%= hfTarifValue.ClientID %>').val('');
                }
            }

            function LoadYearReport() {
                var debtorId = $('#<%= ddlDebtor.ClientID%> option:selected').val();
                var debtorSectorId = $('#<%= hfDebtorSectorId.ClientID %>').val();
                var subsubsectorId = $('#<%= ddlSubSubSector.ClientID%> option:selected').val();
                //alert(debtorSectorId); alert(subsubsectorId);
                $yearReport = $('#<%= ddlTahunLapKeu.ClientID %>');
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getImpositionYearReport.ashx?debtorid=' + debtorId + '&debtorsectorid=' + debtorSectorId + '&subsubsectorid=' + subsubsectorId + ' ") %>';
                $.ajax({
                    type: 'POST',
                    url: handlerUrl,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        //alert(datas);
                        if (datas.length > 1) {
                            $yearReport.get(0).options.length = 0;
                            $yearReport.get(0).options[0] = new Option("-- pilih tahun --", "");
                            $.each(datas, function (i, data) {
                                $yearReport.append('<option value="' + data.YearReport + '">' + data.YearReport + '</option>');
                            });
                        }
                        else {
                            $yearReport.append('<option value="' + datas[0].YearReport + '">' + datas[0].YearReport + '</option>');
                        }
                    },
                    error: function () {
                        alert('Error load tahun!');
                    }
                });
            }
            $('#<%= ddlTahunLapKeu.ClientID %>').change(function () {
                var subsubsectorid = $('#<%= ddlSubSubSector.ClientID %>').val();
                var debtorsectorid = $('#<%= hfDebtorSectorId.ClientID %>').val();
                var year = $('#<%= ddlTahunLapKeu.ClientID %>').val();
                $subSubSectors = $('#<%= ddlSubSubSector.ClientID %>');
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getrecimpositionbyyearreport.ashx?yearreport=' + year + '&subsubsectorid=' + subsubsectorid + '&debtorsectorid=' + debtorsectorid + '") %>';
                if (subsubsectorid > 0 && debtorsectorid && year > 0) {
                    jQuery.ajax({
                        type: 'POST',
                        url: handlerUrl,
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (data) {
                            if (data.YearReport != 0) {

                                //                                var unformatdebtorvalue = accounting.unformat(parseFloat(data.DebtorValue), ",", "."); // Revert to en-US format
                                //                                $('#<%= txtDebtorValue.ClientID %>').val(accounting.formatNumber(unformatdebtorvalue, 2, ".", ",")); // Set to id-ID format
                                //                                var unformatojkvalue = accounting.unformat(parseFloat(data.OJKValue), ",", "."); // Revert to en-US format
                                //                                $('#<%= txtOJKValue.ClientID %>').val(accounting.formatNumber(unformatojkvalue, 2, ".", ",")); // Set to id-ID format


                                var unformatdebtorvalue = parseFloat(data.DebtorValue);
                                //$('#<%= txtDebtorValue.ClientID %>').val(unformatdebtorvalue.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtDebtorValue.ClientID %>').val(data.DebtorValue); // Set to id-ID format

                                var unformatojkvalue = parseFloat(data.OJKValue);
                                //$('#<%= txtOJKValue.ClientID %>').val(unformatojkvalue.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtOJKValue.ClientID %>').val(data.OJKValue); // Set to id-ID format

                                $('#<%= hfImpositionID.ClientID %>').val(data.ImpositionID);

                                $('#<%= hfIsFormula.ClientID %>').val(data.IsFormula);
                                $('#<%= hfTarifId.ClientID %>').val(data.TariffID);

                                var unformattarifvalue = parseFloat(data.Value);
                                //$('#<%= hfTarifValue.ClientID %>').val(unformattarifvalue.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= hfTarifValue.ClientID %>').val(data.Value); // Set to id-ID format

                                var unformattarifMax = parseFloat(data.MaxValue);
                                //$('#<%= txtTarifMax.ClientID %>').val(unformattarifMax.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtTarifMax.ClientID %>').val(data.MaxValue); // Set to id-ID format

                                var unformattarifMin = parseFloat(data.MinValue);
                                //$('#<%= txtTarifMin.ClientID %>').val(unformattarifMin.formatMoney(2, ".", ",")); // Set to id-ID format
                                $('#<%= txtTarifMin.ClientID %>').val(data.MinValue); // Set to id-ID format

                                $('#<%= txtPercentage.ClientID %>').val(data.Percentage);
                                if (data.ImpositionBaseId != 0)
                                    $('#<%= ddlImpositionBase.ClientID%>').val(data.ImpositionBaseId);
                                if (debtorId != "") {
                                    $('#btnSave').button('disable', true);
                                    $('#<%= txtDebtorValue.ClientID %>').attr('disabled', 'disabled');
                                }
                            }
                            else {
                                $('#<%= txtDebtorValue.ClientID %>').val('0, 00');
                                $('#<%= txtOJKValue.ClientID %>').val('0, 00');
                                $('#<%= hfImpositionID.ClientID %>').val(0);
                                if (debtorId != "") {
                                    $('#btnSave').button('enable', true);
                                    $('#<%= txtDebtorValue.ClientID %>').removeAttr('disabled');
                                }
                                GetTariff();
                            }
                        },
                        error: function () {
                            alert('Error!');
                        }
                    });
                }
                else {
                    $('#<%= txtDebtorValue.ClientID %>').val('0, 00');
                    $('#<%= txtOJKValue.ClientID %>').val('0, 00');
                    $('#<%= hfImpositionID.ClientID %>').val(0);
                    //$('#btnSave').button('enable', true);
                    //$('#<%= txtDebtorValue.ClientID %>').removeAttr('disabled');
                }

                //setGrid();
                //refreshGrid();
            });

            function GetDebtor() {
                var debtorId = "<%= base.DebtorID %>";
                var userTypeId = "<%= base.UserTypeID %>";
                var subsubsectors = "<%= base.SubSubSectorIDs %>";
                var handlerUrl = "";
                if (userTypeId == 2) {
                    $('#<%= txtOJKValue.ClientID %>').attr('disabled', 'disabled');
                    handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getdebtor.ashx?method=getbyid&debtorID=' + debtorId + '") %>';
                }
                else if (userTypeId == 3) {
                    //$('#<%= txtDebtorValue.ClientID %>').attr('disabled', 'disabled');
                    handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getdebtor.ashx?method=getbysubsubsector&subsubsectors=' + subsubsectors + '") %>';
                }
                $debtor = $('#<%= ddlDebtor.ClientID %>');
                //$('#ddlDebtor').find('option:not(:first)').remove();
                $.ajax({
                    type: 'POST',
                    url: handlerUrl,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        if (datas.length > 1) {
                            $debtor.get(0).options[0] = new Option("-- pilih debitur --", "");
                            $.each(datas, function (i, data) {
                                $debtor.append('<option value="' + data.DebtorID + '">' + data.DebtorCode + ' - ' + data.DebtorName + '</option>');
                            });
                            $debtor.combobox('autocomplete', "", "-- pilih debitur --");
                            //$debtor.parent().find("a.ui-button").button("disable");
                        }
                        else {
                            $debtor.append('<option value="' + datas[0].DebtorID + '">' + datas[0].DebtorCode + ' - ' + datas[0].DebtorName + '</option>');
                            $debtor.combobox('autocomplete', datas[0].DebtorID, datas[0].DebtorCode + ' - ' + datas[0].DebtorName);

                            //GetSubSubSector();

                        }
                        GetSubSector();
                    },
                    error: function () {
                        alert('Error load debitur!');
                    }
                });
            }

            function GetSubSubSector() {
                //$('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
                $('#<%= ddlSubSubSector.ClientID %>').find('option:not(:first)').remove();
                var debtorId = $('#<%= ddlDebtor.ClientID%> option:selected').val();
                var subsectorid = $('#<%= ddlSubSector.ClientID%> option:selected').val();
                $subSubSectors = $('#<%= ddlSubSubSector.ClientID %>');
                if (subsectorid > 0) {
                    //var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsubsector.ashx?method=getbyDebtorId&debtorid=") %>';
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsubsector.ashx?method=getbydebtorid_subsectorid_AND_subsubsectorids&subsector_id=' + subsectorid + '&debtorid=' + debtorId + ' ") %>';
                    $.ajax({
                        type: 'POST',
                        //url: handlerUrl + debtorId,
                        url: handlerUrl,
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (datasubsubs) {
                            if (datasubsubs.length > 1) {
                                $subSubSectors.get(0).options.length = 0;
                                $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                                $.each(datasubsubs, function (i, datasubsub) {
                                    $subSubSectors.append('<option value="' + datasubsub.SubSubSectorID + '">' + datasubsub.SubSubSectorCode + ' - ' + datasubsub.SubSubSectorName + '</option>');
                                });
                                $subSubSectors.combobox('autocomplete', "", "-- pilih sub sub sektor --");
                            }
                            else {
                                $subSubSectors.append('<option value="' + datasubsubs[0].SubSubSectorID + '">' + datasubsubs[0].SubSubSectorCode + ' - ' + datasubsubs[0].SubSubSectorName + '</option>');
                                $subSubSectors.combobox('autocomplete', datasubsubs[0].SubSubSectorID, datasubsubs[0].SubSubSectorCode + ' - ' + datasubsubs[0].SubSubSectorName);
                                $subSubSectors.trigger("change");
                            }
                        },
                        error: function () {
                            alert('Error!');
                        }
                    });
                }
                else {
                    $subSubSectors.get(0).options.length = 0;
                    $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                }
            }

            function GetSubSector() {
                var debtorid = $("#<%= ddlDebtor.ClientID%> option:selected").val();
                $subSectors = $('#<%= ddlSubSector.ClientID%>');
                $subSectors.get(0).options.length = 0;
                $subsubsector = $('#<%= ddlSubSubSector.ClientID%>');
                // $('#ddlDebtorSector').find("option").remove();
                $('#<%= ddlSubSubSector.ClientID%>').find('option:not(:first)').remove();
                $('#<%= ddlSubSector.ClientID%>').find('option:not(:first)').remove();
                if (debtorid > 0) {
                    // ambil data sub sector dari tabel debtor sector where debtor id
                    var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsector.ashx?method=getbydebtorid") %>';
                    $.ajax({
                        type: 'POST',
                        url: handlerUrl + "&debtor_id=" + debtorid,
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function (datas) {
                            if (datas.length > 1) {
                                //refresh combo sub sub sector
                                $subsubsector.get(0).options.length = 0;
                                $subsubsector.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                                $subsubsector.combobox('autocomplete', "", "-- pilih sub sub sektor --");
                                //
                                $subSectors.get(0).options[0] = new Option("-- pilih sub sektor --", "");
                                $.each(datas, function (i, data) {
                                    $subSectors.append('<option value="' + data.SubSectorID + '">' + data.SubSectorCode + ' - ' + data.SubSectorName + '</option>');
                                });
                                $subSectors.combobox('autocomplete', "", "-- pilih sub sektor --");
                            }
                            else {
                                $subSectors.append('<option value="' + datas[0].SubSectorID + '">' + datas[0].SubSectorCode + ' - ' + datas[0].SubSectorName + '</option>');
                                $subSectors.combobox('autocomplete', datas[0].SubSectorID, datas[0].SubSectorCode + ' - ' + datas[0].SubSectorName);
                                //$subSubSectors.trigger("change");
                            }
                            GetSubSubSector();
                        },
                        error: function () {
                            alert('Error load sub sector from debtor sector!');
                        }
                    });
                }
            }

            function ClearText() {
                $('#<%= hfIsFormula.ClientID %>').val('');
                $('#<%= hfTarifId.ClientID %>').val('');
                $('#<%= txtPercentage.ClientID %>').val('');
                $('#<%= txtTarifMax.ClientID %>').val('');
                $('#<%= txtTarifMin.ClientID %>').val('');
                $('#<%= hfDebtorSectorId.ClientID %>').val('');
                $('#<%= hfTarifValue.ClientID %>').val('');
                $('#<%= ddlSubSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sub sektor --");
                $('#<%= ddlSubSector.ClientID %>').combobox('autocomplete', "", "-- pilih sub sektor --");
                $('#<%= txtDebtorValue.ClientID %>').val('');
                $('#<%= txtOJKValue.ClientID %>').val('');
                $('#<%= ddlImpositionBase.ClientID %>').val('');
                $('#fileUpload').val('');
                $('#divFileRemarks').html('');
                $('#<%= ddlTahunLapKeu.ClientID %>').val('');
            }

            $('#<%= txtDebtorValue.ClientID %>').inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });
            $('#<%= txtOJKValue.ClientID %>').inputmask("decimal", { radixPoint: ",", autoGroup: true, groupSeparator: ".", groupSize: 3, digits: 2, repeat: 18 });

            $("#btnSave").click(function () {

                if (!validator.validate())
                    return;

                var debtorid = $('#<%= ddlDebtor.ClientID%> option:selected').val();
                var subsubsectorid = $('#<%= ddlSubSubSector.ClientID%> option:selected').val();
                var subsectorid = $('#<%= ddlSubSector.ClientID%> option:selected').val();
                var tahunlapkeu = $('#<%= ddlTahunLapKeu.ClientID%> option:selected').val();
                var impositionbaseid = $('#<%= ddlImpositionBase.ClientID%> option:selected').val();
                var percentage = $('#<%= txtPercentage.ClientID%>').val();
                var tarifmin = $('#<%= txtTarifMin.ClientID%>').val();
                var tarifmax = $('#<%= txtTarifMax.ClientID%>').val();
                var debtorvalue = $('#<%= txtDebtorValue.ClientID%>').val();
                var ojkvalue = $('#<%= txtOJKValue.ClientID%>').val();
                var id = $('#<%= hfID.ClientID %>').val();
                var tarifid = $('#<%= hfTarifId.ClientID %>').val();
                var debtorsectorid = $('#<%= hfDebtorSectorId.ClientID %>').val();
                var tarifvalue = $('#<%= hfTarifValue.ClientID %>').val();
                var isformula = $('#<%= hfIsFormula.ClientID %>').val() == 1 ? true : false;
                var impositionid = $('#<%= hfImpositionID.ClientID %>').val();

                var objrecImposition = new Object();
                objrecImposition.ImpositionID = id;
                objrecImposition.DebtorID = encodeURIComponent(debtorid);
                objrecImposition.SubSubSectorID = encodeURIComponent(subsubsectorid);
                objrecImposition.SubSectorID = encodeURIComponent(subsectorid);
                objrecImposition.TahunLapKeu = encodeURIComponent(tahunlapkeu);
                objrecImposition.ImpositionBaseID = encodeURIComponent(impositionbaseid);
                objrecImposition.Percentage = encodeURIComponent(percentage);
                objrecImposition.Minimal = encodeURIComponent(tarifmin);
                objrecImposition.Maximal = encodeURIComponent(tarifmax);
                objrecImposition.DebtorValue = encodeURIComponent(debtorvalue);
                objrecImposition.OJKValue = encodeURIComponent(ojkvalue);
                objrecImposition.TarifID = encodeURIComponent(tarifid);
                objrecImposition.DebtorSectorID = encodeURIComponent(debtorsectorid);
                objrecImposition.TarifValue = encodeURIComponent(tarifvalue);
                objrecImposition.IsFormula = encodeURIComponent(isformula);

                jsonData = JSON.stringify(objrecImposition);

                var param = '&DebtorID=' + debtorid + '&SubSubSectorID=' + subsubsectorid + '&TahunLapKeu=' + tahunlapkeu + '&ImpositionBaseID=' + impositionbaseid + '&IsFormula=' + isformula + '&ImpositionID=' + impositionid + '&SubSectorID=' + subsectorid;
                param += '&Percentage=' + percentage + '&Minimal=' + tarifmin + '&Maximal=' + tarifmax + '&DebtorValue=' + debtorvalue + '&OJKValue=' + ojkvalue + '&TarifID=' + tarifid + '&DebtorSectorID=' + debtorsectorid + '&TarifValue=' + tarifvalue;

                $yearReport = $('#<%= ddlTahunLapKeu.ClientID %>');

                if (id == 0) {
                    var result = window.confirm('Apakah yakin data akan di simpan ?');
                    if (result) {
                        if ($('#fileUpload').val() == '') { // Insert without uploadedfile

                            $.post('<%= ResolveUrl("~/AjaxHandler/Transaction/recImpositionhandler.ashx") %>' + '?method=insertnodialog', param,
                                $("#frmMasterPage")
                                .find("input,textarea,select,hidden")
                                .not("#__VIEWSTATE,#__EVENTVALIDATION")
                                .serialize())
                            .done(function (data) {
                                var r = JSON.parse(data);
                                alert(r.Message);
                                //location.reload();
                                //ClearText();
                                //$('#btnSave').button('disable');
                                //setGrid();
                                //refreshGrid();
                                $yearReport.trigger("change");
                                //location.href = '<%= ResolveUrl("~/lists/Transaction/recImpositionAlllist.aspx") %>';
                            })
                            .fail(function () {
                                alert('Data gagal di simpan!');
                            });

                        }
                        else {
                            var handler = '<%= ResolveUrl("~/AjaxHandler/Transaction/recImpositionhandler.ashx?method=insertnodialog&") %>'
                            $('#frmMasterPage').fileupload('send', {
                                fileInput: $('#fileUpload'),
                                dataType: 'json',
                                url: handler + param
                            })
                        .done(function (e, data) {
                            var x = JSON.stringify(e); // Change from Javascript Object into JSON
                            var y = JSON.parse(x); // Change from JSON into Javascript String
                            alert(y.Message);
                            //location.reload();
                            //ClearText();
                            //$('#btnSave').button('disable');
                            //setGrid();
                            //refreshGrid();
                            $yearReport.trigger("change");
                            //location.href = '<%= ResolveUrl("~/lists/Transaction/recImpositionAlllist.aspx") %>';
                        })
                        .fail(function (e, data) {
                            alert("Data gagal di simpan !");
                        });
                        }
                    }

                }
                else {

                    if ($('#fileUpload').val() == '') { // Update without uploadedfile

                        $.post('<%= ResolveUrl("~/AjaxHandler/Transaction/recImpositionhandler.ashx") %>' + '?method=update',
                                $("#frmMasterPage")
                                .find("input,textarea,select,hidden")
                                .not("#__VIEWSTATE,#__EVENTVALIDATION")
                                .serialize())
                            .done(function (data) {
                                var r = JSON.parse(data);
                                alert(r.Message);
                            })
                            .fail(function () {
                                alert('Data gagal di ubah!');
                            });

                    }
                    else {

                        $('#frmMasterPage').fileupload('send', {
                            fileInput: $('#fileUpload'),
                            dataType: 'json',
                            url: '<%= ResolveUrl("~/AjaxHandler/Transaction/recImpositionhandler.ashx") %>' + '?method=update'
                        })
                        .done(function (e, data) {
                            var x = JSON.stringify(e); // Change from Javascript Object into JSON
                            var y = JSON.parse(x); // Change from JSON into Javascript String
                            alert(y.Message);
                        })
                        .fail(function (e, data) {
                            alert("Data gagal di ubah !");
                        });

                    }
                }

                parent.$('#dialog').dialog('close');

                setTimeout("parent.$('#table').trigger('reloadGrid');", 3000);

                return false;

            });

        });

    </script>
    <style type="text/css">
        .style1
        {
            width: 8px;
        }
        .style2
        {
            width: 165px;
        }
    </style>
    <div>
        <table border="0">
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Debitur
                </td>
                <td>
                    :
                </td>
                <td colspan="2">
                    <asp:DropDownList ID="ddlDebtor" runat="server" Width="250">
                    </asp:DropDownList>
                    &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*</span>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Sub Sektor
                </td>
                <td>
                    :
                </td>
                <td colspan="2">
                    <asp:DropDownList ID="ddlSubSector" runat="server" Width="250">
                    </asp:DropDownList>
                    &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*</span>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Sub Sub Sektor
                </td>
                <td>
                    :
                </td>
                <td colspan="2">
                    <asp:DropDownList ID="ddlSubSubSector" runat="server" Width="250">
                    </asp:DropDownList>
                    &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*</span>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Tahun Laporan Keuangan
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <asp:DropDownList ID="ddlTahunLapKeu" runat="server" Width="100">
                    </asp:DropDownList>
                    &nbsp;<span style="color: Red;">*</span>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Dasar Pengenaan
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <asp:DropDownList ID="ddlImpositionBase" Enabled="false" runat="server" Width="280">
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Tarif
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <asp:TextBox ID="txtPercentage" runat="server" Width="40" Enabled="false"></asp:TextBox>
                </td>
                &nbsp;&nbsp;
                <td>
                    &nbsp;&nbsp; Min
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="txtTarifMin" runat="server" Width="150" Enabled="false"></asp:TextBox>
                </td>
                <td>
                    Max
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="txtTarifMax" runat="server" Width="150" Enabled="false"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Nilai Pengenaan Debitur
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <asp:TextBox ID="txtDebtorValue" runat="server" Width="265" Style="text-align: right"></asp:TextBox>&nbsp;<span
                        style="color: Red;">*</span>
                </td>
            </tr>
            <tr id="trnilaipengenaanOJK">
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Nilai Pengenaan OJK
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <asp:TextBox ID="txtOJKValue" runat="server" Width="265" Style="text-align: right"></asp:TextBox>&nbsp;<span
                        style="color: Red;">*</span>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;
                </td>
                <td style="width: 50">
                    Lampiran
                </td>
                <td>
                    :
                </td>
                <td class="style2">
                    <input type="file" id="fileUpload" />
                    <div id="divFileRemarks">
                    </div>
                </td>
            </tr>
        </table>
        <table border="0">
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
                <td>
                    <div style="text-align: right; padding-top: 10px;">
                        <button id="btnSave" type="button">
                            Simpan</button>
                        <button id="btnClose" type="reset">
                            Batal</button>
                    </div>
                </td>
            </tr>
        </table>
        <br />
        <table border="0">
            <tr>
                <td colspan="2">
                    <table id="table" class="scroll" cellpadding="0" cellspacing="0">
                    </table>
                    <div id="pager" class="scroll">
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
                <td>
                    <asp:HiddenField ID="hfID" runat="server" />
                    <asp:HiddenField ID="hfDebtorSectorId" runat="server" />
                    <asp:HiddenField ID="hfTarifId" runat="server" />
                    <asp:HiddenField ID="hfTarifValue" runat="server" />
                    <asp:HiddenField ID="hfIsFormula" runat="server" />
                    <asp:HiddenField ID="hfImpositionID" runat="server" />
                </td>
            </tr>
        </table>
    </div>
</asp:Content>
